package com.quick.develop.flowable.service.task.impl;

import cn.hutool.core.collection.CollUtil;
import com.quick.develop.framework.common.page.PageResult;
import com.quick.develop.framework.utils.PageUtils;
import com.quick.develop.framework.utils.StringUtils;
import com.quick.develop.flowable.domain.job.BpmDeadJobPageItemRspVO;
import com.quick.develop.flowable.domain.job.BpmDeadJobPageReqVO;
import com.quick.develop.flowable.framework.convert.job.BpmDeadJobConvert;
import com.quick.develop.flowable.framework.factory.FlowServiceFactory;
import com.quick.develop.flowable.service.task.IBpmJobService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.job.api.DeadLetterJobQuery;
import org.flowable.job.api.Job;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author junyuan.liu
 * @description:
 * @date 2022/9/20 19:25
 */
@Service
@Slf4j
public class BpmJobServiceImpl extends FlowServiceFactory implements IBpmJobService {

    @Value("${flowable.async-executor-number-of-retries}")
    private int asyncExecutorNumberOfRetries;


    @Override
    public PageResult<BpmDeadJobPageItemRspVO> deadLetterPage(BpmDeadJobPageReqVO reqVO) {
        DeadLetterJobQuery deadLetterJobQuery = managementService.createDeadLetterJobQuery();
        if (StringUtils.isNotEmpty(reqVO.getProcessInstanceId())) {
            deadLetterJobQuery.processInstanceId(reqVO.getProcessInstanceId());
        }
        if (StringUtils.isNotEmpty(reqVO.getElementId())) {
            deadLetterJobQuery.elementId(reqVO.getElementId());
        }
        if (StringUtils.isNotEmpty(reqVO.getElementName())) {
            deadLetterJobQuery.elementName(reqVO.getElementName());
        }

        List<Job> list = deadLetterJobQuery.listPage(PageUtils.getStart(reqVO), reqVO.getPageSize());
        if (CollUtil.isEmpty(list)) {
            return PageResult.empty(deadLetterJobQuery.count());
        }

        return new PageResult<>(BpmDeadJobConvert.INSTANCE.convertList(list), deadLetterJobQuery.count());
    }

    @Override
    public void restoreDeadJob(String id) {
        managementService.moveDeadLetterJobToExecutableJob(id, asyncExecutorNumberOfRetries);
    }

    @Override
    public String getDeadLetterJobExceptionStacktrace(String id) {
        return managementService.getDeadLetterJobExceptionStacktrace(id);
    }
}
